package com.itsu.vtalk.component.interceptor;

import com.itsu.vtalk.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author suben
 * @createtime 2020/6/21 9:40
 **/
public class LoginInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        System.err.println(request.getRequestURI());
        if (user != null) {
            return true;
        } else {

            if (StringUtils.isNotBlank(request.getHeader("token"))){
                return true;
            }


            if (ServletUtil.isAjax(request)) {
                try (PrintWriter pw = response.getWriter()) {
                    pw.write("<script> top.location.href='/login?kickout=true' </script>");
                    pw.flush();
                } catch (IOException e) {
                    logger.error("write ajax script error", e);
                }
            } else {
                request.setAttribute("kickout", true);
                request.getRequestDispatcher("/login").forward(request, response);
            }
            return false;
        }
    }

}
